<%@ include file="/WEB-INF/jsp/common/IncludeTop.jsp"%>
<%@page pageEncoding="UTF-8"%>
<!-- <link rel="stylesheet" href="jquery-ui/themes/themes/ui-lightness/jquery-ui.css"> -->

<link rel="stylesheet" href="zTree/css/zTreeStyle/zTreeStyle.css" type="text/css">
<link rel="stylesheet" href="zTree/css/metroStyle/metroStyle.css" type="text/css">
<script type="text/javascript" src="datepicker/js/bootstrap-datepicker.js"></script>
<script type="text/javascript" src="datepicker/js/bootstrap-datepicker.ja.min.js"></script>
<script type="text/javascript" src="zTree/js/jquery.ztree.all-3.5.min.js"></script>
<style>
.ui-datepicker {
	font-size: 10px;
}
</style>
<c:if test="${not empty message}">
  <div class="message green">${message}</div>
</c:if>
<div class="container-fluid">
  <div class="col-lg-0 col-lg-offset-0">
    <div class="panel-group" id="accordion">
      <div class="panel panel-primary">
        <div class="panel-heading">
          <h3 class="panel-title">
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne"><spring:message
                code="label.organization"
              /><span style="float: right;">▼</span></a>
          </h3>
        </div>
        <div id="collapseOne" class="panel-collapse collapse in">
          <div class="panel-body">
            <div class="row col-lg-12">
              <form:form id="submitForm" class="form-horizontal" method="get"
                modelAttribute="organization" action="organizationInfo.web"
              >
                <fieldset>
                  <legend>
                    <spring:message code="label.orgSelect" />
                  </legend>
                  <!-- 基準日-->
                  <div class="form-group">
                    <label for="searchDate" class="col-lg-2 control-label"><spring:message
                        code="label.searchDate"
                      /></label>
                    <div class="date form_date col-lg-5" data-date-viewmode="years">
                      <input readonly="readonly" path="effStartDate" type="text"
                        class="form-control" id="searchDate"
                        placeholder="<spring:message code="label.searchDate"/>"
                        value="${searchDate}"
                      />
                    </div>
                  </div>
                  <!-- 取引先会社名 -->
                  <div class="form-group">
                    <label for="select" class="col-lg-2 control-label"><spring:message
                        code="label.customername"
                      /></label>
                    <div class="col-lg-5">
                      <select class="form-control" id="selectCustomer">
                        <option value="0" selected>----------</option>
                        <c:forEach items="${customerList}" var="customerList">
                          <option value="${customerList.customercd}">${customerList.customername}</option>
                        </c:forEach>
                      </select>
                    </div>
                  </div>
                  <!-- 卸会社 -->
                  <div class="form-group">
                    <label for="select" class="col-lg-2 control-label"><spring:message
                        code="label.whsName"
                      /></label>
                    <div class="col-lg-5">
                      <select class="form-control" id="selectOrg" path="whsCd">
                        <option value="0" selected>----------</option>
                      </select>
                    </div>
                  </div>
                </fieldset>
                <fieldset>
                  <div class="form-group">
                    <div class="col-lg-10 col-lg-offset-2">
                      <button type="reset" class="btn btn-default btn-sm">
                        <spring:message code="label.clear" />
                      </button>
                    </div>
                  </div>
                </fieldset>
              </form:form>
            </div>
            <div class="row col-lg-12">
              <!-- テーブル内容 -->
              <div class="well">
                <table class="table table-striped table-hover ">
                  <thead>
                    <tr>
                      <th>ユーザー</th>
                      <th>ホールディングス</th>
                      <th>卸会社</th>
                      <th>階層数</th>
                      <th>適用開始日</th>
                      <th>適用終了日</th>
                      <th>組織変更</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr class="info" id="tableInfo">
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div id="orgInfo" class="panel panel-primary collapse">
        <div class="panel-body">
          <div class="bb-alert alert alert-info col-xs-3 col-xs-offset-4" style="display: none;">
            <span></span>
          </div>
          <div class="col-md-12 col-md-offset-0">
            <ul id="orgTree" class="ztree"></ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<script type="text/javascript">
    $(function() {
        $('#searchDate').datepicker({
            format : 'yyyy-mm-dd',
            language : 'ja',
            showWeek : true,
            firstDay : 1,
            autoSize : true
        });

    });
</script>
<script type="text/javascript">
    $(function() {
        $("#selectCustomer").change(
                function() {
                    var value = $("#selectCustomer option:selected").val();
                    var today = $("#searchDate").val();
                    console.log("param: " + value + " | " + today);
                    //Ajax
                    $.ajax({
                        url : 'organizationList.web',
                        data : {
                            customerCd : value,
                            startDate : today
                        },
                        type : 'GET',
                        dataType : 'json',
                        success : function(data) {
                            success(data);
                            $("#selectOrg").html("");
                            $("#tableInfo").html("");
                            $("#selectOrg").append(
                                    "<option value="+"0"+" selected>" + "--------" + "</option>");
                            for (var i = 0; i < data.length; i++) {
                                $("#selectOrg").append(
                                        "<option value="+data[i].whsCd+">" + data[i].whsNm
                                                + "</option>");
                            }
                        },
                        error : function(XMLHttpRequest, textStatus, errorThrown) {
                            error(XMLHttpRequest, textStatus, errorThrown);
                        }
                    });

                })
    });

    $(function() {
        $("#selectOrg")
                .change(
                        function() {
                            var value = $("#selectOrg option:selected").val();
                            var today = $("#searchDate").val();
                            console.log("param: " + value + " | " + today);
                            //Ajax
                            $
                                    .ajax({
                                        url : 'organizationInfo.web',
                                        data : {
                                            whsCd : value,
                                            startDate : today
                                        },
                                        type : 'GET',
                                        contentType : "application/x-www-form-urlencoded; charset=UTF-8",
                                        dataType : "json",
                                        success : function(data) {
                                            //success(data);
                                            $("#tableInfo").html("");
                                            for (var i = 0; i < data.length; i++) {
                                                $("#tableInfo")
                                                        .append(
                                                                "<td>"
                                                                        + data[i].customerName
                                                                        + "</td>"
                                                                        + "<td>"
                                                                        + data[i].holdingName
                                                                        + "</td>"
                                                                        + "<td>"
                                                                        + data[i].whsName
                                                                        + "</td>"
                                                                        + "<td style=" + "'display: none'" + ">"
                                                                        + data[i].whsCd
                                                                        + "</td>"
                                                                        + "<td style=" + "'display: none'" + ">"
                                                                        + data[i].whsSubCd
                                                                        + "</td>"
                                                                        + "<td>"
                                                                        + data[i].layer
                                                                        + "</td>"
                                                                        + "<td>"
                                                                        + data[i].startDate
                                                                        + "</td>"
                                                                        + "<td>"
                                                                        + data[i].endDate
                                                                        + "</td>"
                                                                        + "<td><button data-toggle='collapse' data-target='#orgInfo' class='btn btn-primary btn-xs' onclick='setWhsCd("
                                                                        + "\"" + data[i].whsCd
                                                                        + "\"" + "," + "\""
                                                                        + data[i].whsSubCd + "\""
                                                                        + "); createTree(" + "\""
                                                                        + data[i].whsCd + "\""
                                                                        + ");'>組織変更</button></td>");
                                            }
                                        },
                                        error : function(XMLHttpRequest, textStatus, errorThrown) {
                                            error(XMLHttpRequest, textStatus, errorThrown);
                                        }
                                    });
                        })
    });

    // Ajax通信成功時処理
    function success(data) {
        console.log("data: " + data);
    };

    // Ajax通信失敗時処理
    function error(XMLHttpRequest, textStatus, errorThrown) {
        alert("error:" + XMLHttpRequest);
        alert("status:" + textStatus);
        alert("errorThrown:" + errorThrown);
    }
</script>
<script>
    $(function() {
        Example.init({
            "selector" : ".bb-alert"
        });
    });
</script>
<script type="text/javascript">
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //January is 0!
    var yyyy = today.getFullYear();

    if (dd < 10) {
        dd = '0' + dd
    }

    if (mm < 10) {
        mm = '0' + mm
    }

    today = mm + '/' + dd + '/' + yyyy;
    today = yyyy + '/' + mm + '/' + dd;

    var log, className = "dark";
    var treeID = "orgTree";
    var curDragNodes, autoExpandNode;
    var newCount = 1;
    var whscd;
    var whssubcd

    function setWhsCd(whsCd, whsSubCd) {
        whscd = whsCd;
        whssubcd = whsSubCd;
        return false;
    }

    var setting = {
        async : {
            enable : true,
            type : "get",
            //contentType: "application/json",
            url : 'organizationNode.web',
            autoParam : [
                    "id", "name", "pId"
            ],
        //otherParam : [  ]
        },

        check : {//display checkbox / radio ,default:false
            enable : false
        },

        data : {
            simpleData : {
                enable : true,
                idKey : "id",
                pIdKey : "pId",
                rootPId : null
            }
        },

        edit : {
            enable : true,
            editNameSelectAll : true,
            showRemoveBtn : showRemoveBtn,
            showRenameBtn : showRenameBtn,
            removeTitle : "削除",
            renameTitle : "編集",
            drag : {
                autoExpandTrigger : true,
                prev : dropPrev,
                inner : dropInner,
                next : dropNext
            }
        },

        view : {
            addHoverDom : addHoverDom,
            removeHoverDom : removeHoverDom,
            selectedMulti : false
        },

        callback : {
            dblClickExpand : dblClickExpand,

            beforeExpand : beforeExpand,
            onAsyncSuccess : onAsyncSuccess,
            onAsyncError : onAsyncError,

            beforeEditName : beforeEditName,
            beforeRemove : beforeRemove,
            beforeRename : beforeRename,
            onRemove : onRemove,
            onRename : onRename,

            beforeDrag : beforeDrag,
            beforeDrop : beforeDrop,
            beforeDragOpen : beforeDragOpen,
            onDrag : onDrag,
            onDrop : onDrop,
            onExpand : onExpand
        }
    };

    function dblClickExpand(treeId, treeNode) {
        return treeNode.level > 0;
    }

    function beforeEditName(treeId, treeNode) {
        className = (className === "dark" ? "" : "dark");
        var zTree = $.fn.zTree.getZTreeObj(treeID);
        zTree.selectNode(treeNode);
        return confirm(" 下記のノード：-- " + treeNode.name + " を編集しますか？");
    }
    function beforeRemove(treeId, treeNode) {
        className = (className === "dark" ? "" : "dark");
        var zTree = $.fn.zTree.getZTreeObj(treeID);
        zTree.selectNode(treeNode);
        return confirm("下記のノード-- " + treeNode.name + " を削除しますか？");
    }
    function beforeRename(treeId, treeNode, newName, isCancel) {
        className = (className === "dark" ? "" : "dark");
        if (newName.length == 0) {
            alert("ノード名を入力してください。");
            var zTree = $.fn.zTree.getZTreeObj(treeID);
            setTimeout(function() {
                zTree.editName(treeNode)
            }, 10);
            return false;
        }
        return true;
    }
    function onRemove(e, treeId, treeNode) {
        $.ajax({
            url : 'organizationNodeDel.web',
            data : {
                id : treeNode.id
            },
            type : 'POST',
            success : function(data) {
                alert(data);
            }
        });

    }
    function onRename(e, treeId, treeNode, isCancel) {
        var nameBfo = treeNode.name;
        $.ajax({
            url : 'organizationNodeRename.web',
            data : {
                id : treeNode.id,
                name : treeNode.name
            },
            type : 'POST',
            success : function(data) {
                alert("ノード名を「" + treeNode.name + "」に編集しました。 ");
            }
        });

    }

    function showRemoveBtn(treeId, treeNode) {
        //return !treeNode.isFirstNode;
        return true;
    }
    function showRenameBtn(treeId, treeNode) {
        //return !treeNode.isFirstNode;
        return true;
    }

    function dropPrev(treeId, nodes, targetNode) {

        var pNode = targetNode.getParentNode();
        if (pNode && pNode.dropInner === false) {
            return false;
        } else {
            for (var i = 0, l = curDragNodes.length; i < l; i++) {
                var curPNode = curDragNodes[i].getParentNode();
                if (curPNode && curPNode !== targetNode.getParentNode()
                        && curPNode.childOuter === false) {
                    return false;
                }
            }
        }
        return true;
    }
    function dropInner(treeId, nodes, targetNode) {

        if (targetNode && targetNode.dropInner === false) {
            return false;
        } else {
            for (var i = 0, l = curDragNodes.length; i < l; i++) {
                if (!targetNode && curDragNodes[i].dropRoot === false) {
                    return false;
                } else if (curDragNodes[i].parentTId
                        && curDragNodes[i].getParentNode() !== targetNode
                        && curDragNodes[i].getParentNode().childOuter === false) {
                    return false;
                }
            }
        }
        return true;
    }
    function dropNext(treeId, nodes, targetNode) {

        var pNode = targetNode.getParentNode();
        if (pNode && pNode.dropInner === false) {
            return false;
        } else {
            for (var i = 0, l = curDragNodes.length; i < l; i++) {
                var curPNode = curDragNodes[i].getParentNode();
                if (curPNode && curPNode !== targetNode.getParentNode()
                        && curPNode.childOuter === false) {
                    return false;
                }
            }
        }
        return true;
    }

    function addHoverDom(treeId, treeNode) {
        var sObj = $("#" + treeNode.tId + "_span");

        if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
        var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
                + "' title='追加' onfocus='this.blur();'></span>";

        sObj.after(addStr);

        var btn = $("#addBtn_" + treeNode.tId);

        //ノード追加モーダル生成
        if (btn)
            btn
                    .bind(
                            "click",
                            function() {
                                bootbox
                                        .dialog({
                                            title : "組織詳細情報",
                                            message : '<div class="container-fluid">'
                                                    + '<div class="row">'
                                                    + '<div class="col-md-12">'
                                                    + '<form id="orgModalform" class="form-horizontal" data-async action="/organizationNode.web" method="POST">'
                                                    + '<fieldset>'
                                                    + '<div class="form-group">'
                                                    + '<label class="col-xs-4 control-label for="inputSmall">卸コード</label>'
                                                    + '<div class="col-xs-4">'
                                                    + '<input class="form-control input-sm" type="text" readonly="readonly" id="whsCd" name="whsCd" value="'+ whscd +'">'
                                                    + '</div></div>'
                                                    + '<div class="form-group">'
                                                    + '<label class="col-xs-4 control-label for="inputSmall">卸サブコード</label>'
                                                    + '<div class="col-xs-4">'
                                                    + '<input class="form-control input-sm" type="text" readonly="readonly" id="whsSubCd" name="whsSubCd" value="'+ whssubcd +'">'
                                                    + '</div></div>'
                                                    + '<div class="form-group">'
                                                    + '<label class="col-xs-4 control-label for="inputSmall">開始終了日</label>'
                                                    + '<div class="date form_date col-xs-4">'
                                                    + '<input class="form-control input-sm" id="dpModal" name="startEndDay" maxlength="10" type="text" readonly="readonly">'
                                                    + '</div></div>'
                                                    + '<div class="form-group">'
                                                    + '<label class="col-xs-4 control-label for="inputSmall">卸部署名</label>'
                                                    + '<div class="col-xs-4">'
                                                    + '<input class="form-control input-sm" type="text" id="whsOrgNm" name="whsOrgNm" placeholder="卸部署名" required>'
                                                    + '</div></div>'
                                                    + '<div class="form-group">'
                                                    + '<label class="col-xs-4 control-label for="inputSmall">卸組織コード桁区</label>'
                                                    + '<div class="col-xs-4">'
                                                    + '<input class="form-control input-sm" type="text" id="whsOrgCd" name="whsOrgCd" placeholder="卸組織コード桁区">'
                                                    + '</div></div>'
                                                    + '<div class="form-group">'
                                                    + '<label class="col-xs-4 control-label for="inputSmall">組織外部連携コード</label>'
                                                    + '<div class="col-xs-4">'
                                                    + '<input class="form-control input-sm" type="text" id="whsDepoCd" name="whsDepoCd" placeholder="組織外部連携コード">'
                                                    + '</div></div>'
                                                    + '<div class="form-group">'
                                                    + '<label class="col-xs-4 control-label for="inputSmall">組織外部連携表示順</label>'
                                                    + '<div class="col-xs-4">'
                                                    + '<input class="form-control input-sm" type="text" id="whsDepoCdSeq" name="whsDepoCdSeq" placeholder="組織外部連携表示順">'
                                                    + '</div></div>' + '</fieldset>'
                                                    + '</form></div></div></div>',

                                            buttons : {
                                                cancel : {
                                                    label : "キャンセル",
                                                    className : "btn-default btn-xs",
                                                    callback : function() {
                                                        var name = $('#whsOrgNm').val()
                                                        Example.show("[" + name
                                                                + "]に対して、組織の追加がキャンセルされました。 ");
                                                    }
                                                },
                                                confirm : {
                                                    label : "確定",
                                                    className : "btn-primary btn-xs",
                                                    callback : function() {
                                                        var nodeName = $('#whsOrgNm').val();
                                                        //ノード追加処理
                                                        addNodeAjax(treeId, treeNode, nodeName);
                                                    }
                                                },
                                            }
                                        });
                            });
    }

    function addNodeAjax(treeId, treeNode, nodeName) {

        var form = $('#orgModalform');
        var element = form.serializeArray();

        var zTree = $.fn.zTree.getZTreeObj(treeID);

        var addAjaxParam = new Array();
        var otherParam = new Array();

        otherParam.push("isRefresh", 1);

        $.each(element, function(i, field) {
            var name = field.name;
            var value = field.value;
            otherParam.push(name, value);
            addAjaxParam.push(name, value);
        });

        //zTree Options
        zTree.setting.async.otherParam = otherParam;
        zTree.addNodes(treeNode, {
            id : (treeNode.id + newCount),
            pId : treeNode.id,
            name : nodeName
        });

        // Ajax Request
        $.ajax({
            url : 'organizationNode.web', //url 
            data : addAjaxParam,
            type : 'POST',
            success : function(data) {
                Example.show("ノードが追加されました。");
                zTree.reAsyncChildNodes(treeNode, "refresh");
            },
            error : function(msg) {
                alert("Error! " + msg);
            }
        });
        newCount++;
        return false;
    }

    function removeHoverDom(treeId, treeNode) {
        $("#addBtn_" + treeNode.tId).unbind().remove();
    }

    function createTree(whsCd) {
        console.log("create tree: " + whsCd);
        //zTreeObj = $.fn.zTree.init($("#" + treeID), setting, zNodes);
        $.ajax({
            url : 'organizationNode.web', //url
            data : {
                isRefresh : 0,
                whsCd : whsCd,
                startDate : today
            },
            type : 'GET',
            timeout : 10000,
            contentType : "application/x-www-form-urlencoded; charset=UTF-8",
            dataType : "text",
            success : function(data) {
                $.fn.zTree.init($("#" + treeID), setting, eval('(' + data + ')'));
            },
            error : function(msg) {
                alert(" Error！" + msg);
            }
        });
    }

    function beforeExpand(treeId, treeNode) {
        if (!treeNode.isAjaxing) {
            return true;
        } else {
            alert("zTree 展開中。。。");
            return false;
        }
    }
    function onAsyncSuccess(event, treeId, treeNode, msg) {
        /* 	var nodes = treeNode.children;	 
         var treeObj = $.fn.zTree.getZTreeObj(treeId); 

         for(var i=0;i<nodes.length;i++){
         //展開
         treeObj.expandNode(nodes[i],true,false,true,true);
         } */
    }
    function onAsyncError() {
        alert(" error");
    }
    function beforeDrag(treeId, treeNodes) {
        className = (className === "dark" ? "" : "dark");
        for (var i = 0, l = treeNodes.length; i < l; i++) {
            if (treeNodes[i].drag === false) {
                curDragNodes = null;
                return false;
            } else if (treeNodes[i].parentTId && treeNodes[i].getParentNode().childDrag === false) {
                curDragNodes = null;
                return false;
            }
        }
        curDragNodes = treeNodes;
        return true;
    }

    function beforeDragOpen(treeId, treeNode) {
        autoExpandNode = treeNode;
        return true;
    }

    function beforeDrop(treeId, treeNodes, targetNode, moveType, isCopy) {
        className = (className === "dark" ? "" : "dark");
        return true;
    }

    function onDrag(event, treeId, treeNodes) {
        className = (className === "dark" ? "" : "dark");
    }

    function onDrop(event, treeId, treeNodes, targetNode, moveType, isCopy) {
        className = (className === "dark" ? "" : "dark");
        $.ajax({
            url : 'asyncDragNodes.web', // url 
            data : {
                id : treeNodes[0].id,
                pid : targetNode.id,
                name : treeNodes[0].name,
                moveType : moveType,
                isCopy : isCopy
            },
            type : 'POST',
            success : function(data) {
            }
        });

    }

    function onExpand(event, treeId, treeNode) {
        if (treeNode === autoExpandNode) {
            className = (className === "dark" ? "" : "dark");
        }
    }
//-->
</script>

<%@ include file="/WEB-INF/jsp/common/IncludeBottom.jsp"%>